package com.ssy.lingxi.pay.serviceimpl;


import cn.hutool.json.JSONObject;
import com.ssy.lingxi.common.constant.order.OrderPayChannelEnum;
import com.ssy.lingxi.common.constant.order.OrderPaymentParameterEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.order.api.feign.OrderFeignService;
import com.ssy.lingxi.order.api.model.vo.request.OrderPayChannelFeignVO;
import com.ssy.lingxi.order.api.model.vo.response.PayChannelParameterFeignDetailVO;
import com.ssy.lingxi.order.api.model.vo.response.PaymentParameterFeignDetailVO;
import com.ssy.lingxi.pay.api.model.vo.request.ccb.B2bRefundQueryVO;
import com.ssy.lingxi.pay.api.model.vo.request.ccb.B2bRefundVO;
import com.ssy.lingxi.pay.model.dto.RefundDTO;
import com.ssy.lingxi.pay.model.dto.RefundQueryDTO;
import com.ssy.lingxi.pay.service.IPayCacheService;
import com.ssy.lingxi.pay.service.IRefundService;
import com.ssy.lingxi.pay.utils.CcbPayUtil;
import com.ssy.lingxi.pay.utils.RefundUtils;
import com.ssy.lingxi.pay.utils.XmlUtil;
import jodd.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author:linzy
 * @date: 2021/12/27
 * @version 2.0.0
 */
@Service
public class RefundServiceImpl  implements IRefundService {

    private final static Logger logger = LoggerFactory.getLogger(RefundServiceImpl.class);

    @Resource
    private IPayCacheService iPayCacheService;

    @Resource
    private OrderFeignService orderFeignService;

    @Override
    public Boolean refund (B2bRefundVO refundVO) {
        try{
            String ipAddress = "";      //外联平台ip地址
            String port = "";           //外联平台端口
            String customerId = "";     //商户号
            String userId = "";         //操作员号
            String password = "";       //操作员密码
            //从订单服务查询支付参数
            OrderPayChannelFeignVO orderPayChannelFeignVO = new OrderPayChannelFeignVO();
            orderPayChannelFeignVO.setPayChannel(OrderPayChannelEnum.CCB_B2B);
            Wrapper<PaymentParameterFeignDetailVO> parameterResult = orderFeignService.findPlatformPaymentParameters(orderPayChannelFeignVO);
            if (parameterResult.getCode() != ResponseCode.SUCCESS.getCode()) {
                throw new BusinessException(parameterResult.getCode(), parameterResult.getMessage());
            }
            if (CollectionUtils.isEmpty(parameterResult.getData().getParameters())) {
                throw new BusinessException(ResponseCode.PAY_CCB_B2B_PARAM_NOT_EXIST);
            }
            List<PayChannelParameterFeignDetailVO> parameters = parameterResult.getData().getParameters();
            for (PayChannelParameterFeignDetailVO p : parameters) {
                if (p.getParameter().equals(OrderPaymentParameterEnum.CCB_B2B_IP_ADDRESS)) {
                    ipAddress = p.getValue();
                }else if (p.getParameter().equals(OrderPaymentParameterEnum.CCB_B2B_PORT)) {
                    port = p.getValue();
                }else if (p.getParameter().equals(OrderPaymentParameterEnum.CCB_B2B_MERCHANT_ID)) {
                    customerId = p.getValue();
                }else if (p.getParameter().equals(OrderPaymentParameterEnum.CCB_B2B_USER_ID)) {
                    userId = p.getValue();
                }else if (p.getParameter().equals(OrderPaymentParameterEnum.CCB_B2B_USER_PASSWORD)) {
                    password = p.getValue();
                }
            }
            if(StringUtil.isEmpty(ipAddress)){
                throw new BusinessException(OrderPaymentParameterEnum.CCB_B2B_IP_ADDRESS.getKey() + ResponseCode.PARAM_NOT_EXIST.getMessage());
            }
            if(StringUtil.isEmpty(port)){
                throw new BusinessException(OrderPaymentParameterEnum.CCB_B2B_PORT.getKey() + ResponseCode.PARAM_NOT_EXIST.getMessage());
            }
            if(StringUtil.isEmpty(customerId)){
                throw new BusinessException(OrderPaymentParameterEnum.CCB_B2B_MERCHANT_ID.getKey() + ResponseCode.PARAM_NOT_EXIST.getMessage());
            }
            if(StringUtil.isEmpty(userId)){
                throw new BusinessException(OrderPaymentParameterEnum.CCB_B2B_USER_ID.getKey() + ResponseCode.PARAM_NOT_EXIST.getMessage());
            }
            if(StringUtil.isEmpty(password)){
                throw new BusinessException(OrderPaymentParameterEnum.CCB_B2B_USER_PASSWORD.getKey() + ResponseCode.PARAM_NOT_EXIST.getMessage());
            }
            //请求序列号
            String requestSn = RefundUtils.getRequestSn();
            //退款金额
            String money = refundVO.getMoney();
            //订单号
            String orderId = refundVO.getOrderId();
            //退款流水号
            String refundCode = refundVO.getRefundCode() == null?"":refundVO.getRefundCode();
            //退款发送请求到外联
            String result = RefundUtils.payByCcbRefund(ipAddress, Integer.parseInt(port), requestSn, userId, password, money, orderId, customerId, refundCode);
            logger.info("B2B商户建行退款响应:"+ result);

            //将返回的xml字符串转成json对象
            JSONObject jsonObject = XmlUtil.xml2Json(result);
            //判断转换之后json是否为空，为空则抛出AssertionError，并终止执行。
            assert jsonObject != null;
            RefundDTO refundDTO = iPayCacheService.deserializeObject(jsonObject.toString(), RefundDTO.class);
            logger.info("xml转json:{}", jsonObject.toString());
            //将结果返回
            if(CcbPayUtil.success_code.equals(refundDTO.getRefundText().getReturnCode())) {
                return true;
            }else{
                throw new BusinessException(refundDTO.getRefundText().getReturnMsg());
            }
//            if(StringUtil.isNotEmpty(refundDTO.getRefundText().getReturnCode())){
//                B2bRefundReturnVO refundReturn = new B2bRefundReturnVO();
//                refundReturn.setOrderId(refundVO.getOrderId());
//                //响应码
//                refundReturn.setReturnCode(refundDTO.getRefundText().getReturnCode());
//                //响应信息
//                refundReturn.setReturnMsg(refundDTO.getRefundText().getReturnMsg());
//
//                return refundReturn;
//            }

        }catch (Exception e){
            throw new BusinessException(ResponseCode.PAY_CCB_GATEWAY_EXCEPTION);
        }
    }

    @Override
    public String refundQuery(B2bRefundQueryVO refundQueryVO) {
        try{
            String ipAddress = "";      //外联平台ip地址
            String port = "";           //外联平台端口
            String customerId = "";     //商户号
            String userId = "";         //操作员号
            String password = "";       //操作员密码
            //从订单服务查询支付参数
            OrderPayChannelFeignVO orderPayChannelFeignVO = new OrderPayChannelFeignVO();
            orderPayChannelFeignVO.setPayChannel(OrderPayChannelEnum.CCB_B2B);
            Wrapper<PaymentParameterFeignDetailVO> parameterResult = orderFeignService.findPlatformPaymentParameters(orderPayChannelFeignVO);
            if (parameterResult.getCode() != ResponseCode.SUCCESS.getCode()) {
                throw new BusinessException(parameterResult.getCode(), parameterResult.getMessage());
            }
            if (CollectionUtils.isEmpty(parameterResult.getData().getParameters())) {
                throw new BusinessException(ResponseCode.PAY_CCB_B2B_PARAM_NOT_EXIST);
            }
            List<PayChannelParameterFeignDetailVO> parameters = parameterResult.getData().getParameters();
            for (PayChannelParameterFeignDetailVO p : parameters) {
                if (p.getParameter().equals(OrderPaymentParameterEnum.CCB_B2B_IP_ADDRESS)) {
                    ipAddress = p.getValue();
                }else if (p.getParameter().equals(OrderPaymentParameterEnum.CCB_B2B_PORT)) {
                    port = p.getValue();
                }else if (p.getParameter().equals(OrderPaymentParameterEnum.CCB_B2B_MERCHANT_ID)) {
                    customerId = p.getValue();
                }else if (p.getParameter().equals(OrderPaymentParameterEnum.CCB_B2B_USER_ID)) {
                    userId = p.getValue();
                }else if (p.getParameter().equals(OrderPaymentParameterEnum.CCB_B2B_USER_PASSWORD)) {
                    password = p.getValue();
                }
            }
            if(StringUtil.isEmpty(ipAddress)){
                throw new BusinessException(OrderPaymentParameterEnum.CCB_B2B_IP_ADDRESS.getKey() + ResponseCode.PARAM_NOT_EXIST.getMessage());
            }
            if(StringUtil.isEmpty(port)){
                throw new BusinessException(OrderPaymentParameterEnum.CCB_B2B_PORT.getKey() + ResponseCode.PARAM_NOT_EXIST.getMessage());
            }
            if(StringUtil.isEmpty(customerId)){
                throw new BusinessException(OrderPaymentParameterEnum.CCB_B2B_MERCHANT_ID.getKey() + ResponseCode.PARAM_NOT_EXIST.getMessage());
            }
            if(StringUtil.isEmpty(userId)){
                throw new BusinessException(OrderPaymentParameterEnum.CCB_B2B_USER_ID.getKey() + ResponseCode.PARAM_NOT_EXIST.getMessage());
            }
            if(StringUtil.isEmpty(password)){
                throw new BusinessException(OrderPaymentParameterEnum.CCB_B2B_USER_PASSWORD.getKey() + ResponseCode.PARAM_NOT_EXIST.getMessage());
            }

            //请求序列号
            String requestSn = RefundUtils.getRequestSn();
            //判断流水类型，查询时间和交易日期相同时，传 【0 未结流水】 查询时间在交易日期不同时，传 【1 已结算流水】
            String kind;
            if(StringUtil.isEmpty(refundQueryVO.getKind())){
                String tradeDate = refundQueryVO.getTradeDate();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String date = sdf.format(new Date());
                if(tradeDate.equals(date)){
                    kind = "0";
                }else{
                    kind = "1";
                }
            }else{
                kind = refundQueryVO.getKind();
            }
//            //流水类型:0:未结流水,1:已结流水
//            String kind = refundQueryVO.getKind();
            //订单号
            String orderId = refundQueryVO.getOrderId();
            //查询退款流水
            String result = RefundUtils.payByCcbRefundQuery(ipAddress, Integer.parseInt(port), requestSn, customerId, userId, password, orderId, kind);
            logger.info("B2B商户建行退款流水查询响应:"+ result.toString());

            //将返回的xml字符串转成json对象
            JSONObject jsonObject = XmlUtil.xml2Json(result);
            //判断转换之后json是否为空，为空则抛出AssertionError，并终止执行。
            assert jsonObject != null;
            RefundQueryDTO refundQueryDTO = iPayCacheService.deserializeObject(jsonObject.toString(), RefundQueryDTO.class);
            logger.info("xml转json:{}", jsonObject.toString());

            //将结果返回
            if(CcbPayUtil.success_code.equals(refundQueryDTO.getRefundQueryInfoDTO().getReturnCode())) {
                return refundQueryDTO.getRefundQueryInfoDTO().getRefundQueryPage().get(0).getRefundQueryInfoList().get(0).getStatus();
            }else{
                throw new BusinessException(refundQueryDTO.getRefundQueryInfoDTO().getReturnMsg());
            }
//            if(StringUtil.isNotEmpty(refundQueryDTO.getRefundQueryInfoDTO().getReturnCode())){
//                B2bRefundQueryReturnVO refundQueryReturn = new B2bRefundQueryReturnVO();
//                refundQueryReturn.setOrderId(refundQueryVO.getOrderId());
//                //响应码
//                refundQueryReturn.setReturnCode(refundQueryDTO.getRefundQueryInfoDTO().getReturnCode());
//                //响应信息
//                refundQueryReturn.setReturnMsg(refundQueryDTO.getRefundQueryInfoDTO().getReturnMsg());
//
//                return refundQueryReturn;
//            }

        }catch (Exception e){
            throw new BusinessException(ResponseCode.PAY_CCB_GATEWAY_EXCEPTION);
        }
    }
}
